<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
       
      <meta name="keywords" content="ES6、JS" />
       
      <meta name="description" content="ES6、JS" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>文件流 |  君书</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="君书" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-文件流"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  文件流
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/06/29/%E6%96%87%E4%BB%B6%E6%B5%81/" class="article-date">
  <time datetime="2022-06-29T06:59:06.000Z" itemprop="datePublished">2022-06-29</time>
</a>   
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">11 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>stream 并非 nodejs 独有的概念。广泛的应用常见：网络 I/O 和磁盘 I/O</p>
<p>nodejs 中 stream 是流操作抽象接口的集合。可读、可写、双工、转换</p>
<p>无 Stream 时存在的问题：</p>
<ol>
<li>同步读取资源文件，等待时间长</li>
<li>资源文件一次性加载到内存，内存消耗大（结合 v8 引擎内存理解）</li>
</ol>
<p>流处理数据的优势：</p>
<ol>
<li>时间效率：同时处理多个 chunk</li>
<li>空间效率：同一时间流无须占据大内存空间</li>
<li>使用方便：配合管道，扩展程序简单</li>
</ol>
<span id="more"></span>

<p>Nodejs 内置了 stream 模块，用于流的操作。Node.js 中有四种基本的流类型：</p>
<ul>
<li><code>Writable</code>: 可以写入数据的流（例如，<code>fs.createWriteStream()</code>）。</li>
<li><code>Readable</code>: 可以从中读取数据的流（数据源）（例如，<code>fs.createReadStream()</code>）。</li>
<li><code>Duplex</code>: <code>Readable</code> 和 <code>Writable</code> 的流（例如，<code>net.Socket</code>）。</li>
<li><code>Transform</code>: 可以在写入和读取数据时修改或转换数据的 <code>Duplex</code> 流（例如，<code>zlib.createDeflate()</code>）。</li>
</ul>
<h4 id="1-自定义可读流"><a href="#1-自定义可读流" class="headerlink" title="1. 自定义可读流"></a>1. 自定义可读流</h4><ol>
<li>继承 stream 的 <code>Readable</code> 接口</li>
<li>重写 <code>_read()</code> 方法调用 <code>push()</code> 产出数据添加到缓存中</li>
</ol>
<p>底层数据读取完后如何处理？给 <code>push</code> 方法传递 <code>null</code> 值</p>
<p>消费者如何获取可读流中的数据？提供 <code>data</code> 和 <code>readable+read</code> 事件（流动模式、暂停模式）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123;Readable&#125; = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 模拟底层数据</span></span><br><span class="line"><span class="keyword">let</span> source = [<span class="string">&#x27;lg&#x27;</span>, <span class="string">&#x27;zce&#x27;</span>, <span class="string">&#x27;syy&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">// 自定义类继承 Readable</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyReadable</span> <span class="keyword">extends</span> <span class="title">Readable</span></span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">source</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>()</span><br><span class="line">    <span class="built_in">this</span>.source = source</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">_read</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> data = <span class="built_in">this</span>.source.shift() || <span class="literal">null</span> </span><br><span class="line">    <span class="built_in">this</span>.push(data)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实例化</span></span><br><span class="line"><span class="keyword">let</span> myReadable = <span class="keyword">new</span> MyReadable(source)</span><br><span class="line"></span><br><span class="line">myReadable.on(<span class="string">&#x27;data&#x27;</span>, <span class="function">(<span class="params">chunk</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(chunk.toString())</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="2-自定义可写流"><a href="#2-自定义可写流" class="headerlink" title="2. 自定义可写流"></a>2. 自定义可写流</h4><ol>
<li>继承 stream 的 Writable</li>
<li>重写 _write 方法调用 write 将缓存中的数据写入</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123;Writable&#125; = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyWriteable</span> <span class="keyword">extends</span> <span class="title">Writable</span></span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>()</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">_write</span>(<span class="params">chunk, en, done</span>)</span> &#123;</span><br><span class="line">    process.stdout.write(chunk.toString() + <span class="string">&#x27;&lt;----&#x27;</span>)</span><br><span class="line">    process.nextTick(done)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myWriteable = <span class="keyword">new</span> MyWriteable()</span><br><span class="line"></span><br><span class="line">myWriteable.write(<span class="string">&#x27;拉勾教育&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;end&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="3-自定义转换流"><a href="#3-自定义转换流" class="headerlink" title="3. 自定义转换流"></a>3. 自定义转换流</h4><ol>
<li>继承 stream 的 Transform</li>
<li>重写 _transform 方法调用 push 将数据进行转换并输出到缓存中</li>
</ol>
<h4 id="4-文件可读流-fs-createReadStream"><a href="#4-文件可读流-fs-createReadStream" class="headerlink" title="4. 文件可读流 fs.createReadStream()"></a>4. 文件可读流 <code>fs.createReadStream()</code></h4><p>encoding： 默认读取的是 <code>Buffer</code> 二进制</p>
<p>fd：文件标识符</p>
<p>mode：文件操作权限，默认 438</p>
<p>highWaterMark：64kb，Readable 流默认为 16kb</p>
<p>文件读取流的事件：<code>open/data/readable/end/close/error</code></p>
<p><code>模拟文件可读流</code>：</p>
<ol>
<li><code>new MyReadStream()</code>时需要执行文件的 <code>open</code>操作，并触发 <code>open</code>事件</li>
<li><code>read()</code>时可通过 <code>once</code>函数订阅 <code>open</code>事件，确保能获取到 <code>fd</code></li>
<li>在读取文件的过程中根据读取内容的长度判断何时触发 <code>data/end/close</code>事件</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>).EventEmitter</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyReadStream</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">path, options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>()</span><br><span class="line">    <span class="built_in">this</span>.path = path</span><br><span class="line">    <span class="built_in">this</span>.flags = options.flags || <span class="string">&quot;r&quot;</span></span><br><span class="line">    <span class="built_in">this</span>.mode = options.mode || <span class="number">438</span></span><br><span class="line">    <span class="built_in">this</span>.autoClose = options.autoClose || <span class="literal">true</span> </span><br><span class="line">    <span class="built_in">this</span>.start = options.start || <span class="number">0</span></span><br><span class="line">    <span class="built_in">this</span>.end = options.end </span><br><span class="line">    <span class="built_in">this</span>.highWaterMark = options.highWaterMark || <span class="number">64</span> * <span class="number">1024</span> </span><br><span class="line">    <span class="built_in">this</span>.readOffset = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.open()</span><br><span class="line">    <span class="built_in">this</span>.on(<span class="string">&#x27;newListener&#x27;</span>, <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(event === <span class="string">&#x27;data&#x27;</span>) &#123;</span><br><span class="line">        <span class="built_in">this</span>.read()</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">open</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    fs.open(<span class="built_in">this</span>.path, <span class="built_in">this</span>.flags, <span class="built_in">this</span>.mode, <span class="function">(<span class="params">err, fd</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;error&#x27;</span>, err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="built_in">this</span>.fd = fd</span><br><span class="line">      <span class="built_in">this</span>.emit(<span class="string">&#x27;open&#x27;</span>, fd)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">read</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> <span class="built_in">this</span>.fd !== <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">this</span>.once(<span class="string">&#x27;open&#x27;</span>, <span class="built_in">this</span>.read)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> buffer = Buffer.alloc(<span class="built_in">this</span>.highWaterMark)</span><br><span class="line">    <span class="keyword">const</span> howMuchToRead = <span class="built_in">this</span>.end ? <span class="built_in">Math</span>.min(<span class="built_in">this</span>.end + <span class="number">1</span> - <span class="built_in">this</span>.readOffset, <span class="built_in">this</span>.highWaterMark) : <span class="built_in">this</span>.highWaterMark</span><br><span class="line">    fs.read(<span class="built_in">this</span>.fd, buffer, <span class="number">0</span>, howMuchToRead, <span class="built_in">this</span>.readOffset, <span class="function">(<span class="params">err, bytesRead, buffer</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;error&#x27;</span>, err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(bytesRead) &#123;</span><br><span class="line">        <span class="built_in">this</span>.readOffset += bytesRead</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;data&#x27;</span>, buffer.slice(<span class="number">0</span>, bytesRead))</span><br><span class="line">        <span class="built_in">this</span>.read()</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;end&#x27;</span>)</span><br><span class="line">        <span class="built_in">this</span>.close()</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">close</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    fs.close(<span class="built_in">this</span>.fd, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;error&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="built_in">this</span>.emit(<span class="string">&#x27;close&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> readStream = <span class="keyword">new</span> MyReadStream(<span class="string">&#x27;test.txt&#x27;</span>, &#123;</span><br><span class="line">  end: <span class="number">7</span>,</span><br><span class="line">  highWaterMark: <span class="number">3</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">readStream.on(<span class="string">&#x27;data&#x27;</span>, <span class="function">(<span class="params">chunk</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(chunk)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">readStream.on(<span class="string">&#x27;open&#x27;</span>, <span class="function">(<span class="params">fd</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;open ----&gt;&#x27;</span>, fd)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">readStream.on(<span class="string">&#x27;close&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;close&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">readStream.on(<span class="string">&#x27;end&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;end&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h4 id="5-文件可写流-fs-createWriteStream"><a href="#5-文件可写流-fs-createWriteStream" class="headerlink" title="5. 文件可写流 fs.createWriteStream()"></a>5. 文件可写流 <code>fs.createWriteStream()</code></h4><p>一个汉字占用三个字节。<code>Writable</code> 要求写入的数据类型为 <code>Buffer/string</code> 。</p>
<p>异步操作成为串行执行。</p>
<p>文件写入流的事件：<code>open/write/end/close/error</code> 。</p>
<ol>
<li><code>error</code> 捕获的是写入过程中的错误，而非写入语法的错误。</li>
<li><code>end()</code> 之后无法再执行写入操作。但可以使用 <code>end(&#39;最后的写入信息放在这里可以实现最后一次写入操作哦&#39;)</code>。</li>
</ol>
<p><code>write() 执行流程：</code></p>
<ol>
<li>第一次调用 write 方法时是将数据直接写入文件中</li>
<li>第二次开始 write 方法就是将数据写入到缓存中</li>
<li>生产速度和消费速度是不一样的，一般情况下生产速度要比消费速度快很多</li>
<li>当 flag 为 false 之后并不意味着当前次的数据不能被写入了，但是我们应该告知数据的生产者，当前的消费速度已经跟不上生产速度了，所以这个时候，一般我们会将可读流的模块修改为暂停模式</li>
<li>当数据生产者暂停后，消费者会慢慢的消化它内部缓存中的数据，直到可以再次被执行写入操作</li>
<li>当缓冲区可以继续写入数据时如何让生产者知道？<code>drain 事件</code></li>
</ol>
<p><code>write() 源码调试</code>：</p>
<ol>
<li><code>writeOrBuffer() 函数</code> <ol>
<li>第一次调用 write 方法时是将数据直接写入文件中。源码中将 <code>state.writing</code> 属性从 false 设置为 true</li>
<li>第一次调用 <code>steam._write() 函数</code>实现文件的写入</li>
<li>第二次开始 write 方法就是将数据写入到缓存中。<code>存放到 state.buffered</code></li>
</ol>
</li>
</ol>
<h4 id="6-链表"><a href="#6-链表" class="headerlink" title="6. 链表"></a>6. 链表</h4><p>存储数据的结构。在 <code>Writeable</code> 中被写入的数据有些是需要在缓存区中进行排队等待的。且遵循先进先出的功能。</p>
<p>数组缺点：</p>
<ol>
<li>数组存储数据的长度有限定</li>
<li>数据存储存在塌陷</li>
</ol>
<p>链表分类：</p>
<ol>
<li>双向链表</li>
<li>单向链表：head+node+null</li>
<li>循环链表</li>
</ol>
<p>单向链表实现：</p>
<ol>
<li>node 节点</li>
<li>LinkList 链表</li>
</ol>
<p>单向链表实现队列：通过链接实现数据的存储。</p>
<ol>
<li>进队列使用链表新增节点的方式进行</li>
<li>出队列使用链表删除节点的方式进行（每次删除的都是链表的第一个节点）</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">element, next</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.element = element;</span><br><span class="line">    <span class="built_in">this</span>.next = next;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkList</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.head = <span class="literal">null</span></span><br><span class="line">    <span class="built_in">this</span>.size = <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">_getNode</span>(<span class="params">index</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span> || index &gt;= <span class="built_in">this</span>.size) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;越界了&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> currentNode = <span class="built_in">this</span>.head</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; index; i++) &#123;</span><br><span class="line">      currentNode = currentNode.next</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> currentNode</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">add</span>(<span class="params">index, node</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">arguments</span>.length === <span class="number">1</span>) &#123;</span><br><span class="line">      node = index</span><br><span class="line">      index = <span class="built_in">this</span>.size</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span> || index &gt; <span class="built_in">this</span>.size) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;cross the border&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(index) &#123;</span><br><span class="line">      <span class="keyword">const</span> preNode = <span class="built_in">this</span>._getNode(index - <span class="number">1</span>)</span><br><span class="line">      preNode.next = <span class="keyword">new</span> Node(node, preNode.next)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.head = <span class="keyword">new</span> Node(node, <span class="built_in">this</span>.head)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.size++</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">remove</span>(<span class="params">index</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span> || index &gt; <span class="built_in">this</span>.size) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;cross the border&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> rmnode = <span class="literal">null</span></span><br><span class="line">    <span class="keyword">if</span>(index) &#123;</span><br><span class="line">      <span class="keyword">const</span> preNode = <span class="built_in">this</span>._getNode(index - <span class="number">1</span>)</span><br><span class="line">      rmnode = preNode.next</span><br><span class="line">      preNode.next = rmnode.next</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      rmnode = <span class="built_in">this</span>.head</span><br><span class="line">      <span class="keyword">if</span>(!rmnode) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">undefined</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="built_in">this</span>.head = rmnode.next</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.size--</span><br><span class="line">    <span class="keyword">return</span> rmnode</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Queue</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.linkList = <span class="keyword">new</span> LinkList()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">enQueue</span>(<span class="params">data</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.linkList.add(data)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">deQueue</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.linkList.remove(<span class="number">0</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="7-文件可写流"><a href="#7-文件可写流" class="headerlink" title="7. 文件可写流"></a>7. 文件可写流</h4><p>highWaterMark：16kb。生产者的生产速度远远高于消费者的消费速度。所以需要在消费跟不上生产时，暂停生产，将缓存中的内容全部消费后，再继续触发生产者生产内容。</p>
<p>文件可写流是异步的，但多个可写流之间的写入顺序是同步的。文件可写流工作流程如下：</p>
<ol>
<li>第一次调用写入方法时，直接写入文件中，不进缓存</li>
<li>第N(N != 1)次调用写入方法时，将要写入的内容放进缓存队列</li>
<li>当第一次写入文件完成后，会从缓存队列中取出内容再次写入，直到缓存队列的内容都被清空</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>).EventEmitter;</span><br><span class="line"><span class="keyword">const</span> Queue = <span class="built_in">require</span>(<span class="string">&#x27;./LinkList&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyWriteStream</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">path, options=&#123;&#125;</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>()</span><br><span class="line">    <span class="built_in">this</span>.path = path</span><br><span class="line">    <span class="built_in">this</span>.flags = options.flags || <span class="string">&#x27;w&#x27;</span></span><br><span class="line">    <span class="built_in">this</span>.mode = options.mode || <span class="number">438</span></span><br><span class="line">    <span class="built_in">this</span>.autoClose = options.autoClose || <span class="literal">true</span> </span><br><span class="line">    <span class="built_in">this</span>.start = options.start || <span class="number">0</span></span><br><span class="line">    <span class="built_in">this</span>.encoding = options.encoding || <span class="string">&#x27;utf8&#x27;</span></span><br><span class="line">    <span class="built_in">this</span>.highWaterMark = options.highWaterMark || <span class="number">16</span>*<span class="number">1024</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.open()</span><br><span class="line">    <span class="built_in">this</span>.writing = <span class="literal">false</span></span><br><span class="line">    <span class="built_in">this</span>.writeLen = <span class="number">0</span></span><br><span class="line">    <span class="built_in">this</span>.needDrain = <span class="literal">false</span> </span><br><span class="line">    <span class="built_in">this</span>.writeOffset = <span class="built_in">this</span>.start</span><br><span class="line">    <span class="built_in">this</span>.cache = <span class="keyword">new</span> Queue()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">open</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    fs.open(<span class="built_in">this</span>.path, <span class="built_in">this</span>.flags, <span class="function">(<span class="params">err, fd</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;error&#x27;</span>, err)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 正常打开</span></span><br><span class="line">      <span class="built_in">this</span>.fd = fd</span><br><span class="line">      <span class="built_in">this</span>.emit(<span class="string">&#x27;open&#x27;</span>, fd)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">write</span>(<span class="params">chunk, encoding, cb</span>)</span> &#123;</span><br><span class="line">    chunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)</span><br><span class="line">    <span class="built_in">this</span>.writeLen += chunk.length</span><br><span class="line">    <span class="keyword">const</span> flag = <span class="built_in">this</span>.writeLen &lt; <span class="built_in">this</span>.highWaterMark</span><br><span class="line">    <span class="built_in">this</span>.needDrain = !flag</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.writing) &#123;</span><br><span class="line">      <span class="comment">// 当前正在执行写入，所以内容应该排队</span></span><br><span class="line">      <span class="built_in">this</span>.cache.enQueue(&#123;chunk, encoding, cb&#125;)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 第一次写入，直接进入到文件内</span></span><br><span class="line">      <span class="built_in">this</span>.writing = <span class="literal">true</span></span><br><span class="line">      <span class="built_in">this</span>._write(chunk, encoding, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        cb &amp;&amp; cb()</span><br><span class="line">        <span class="comment">// 进行下次写入操作，清空缓存队列中的内容</span></span><br><span class="line">        <span class="built_in">this</span>._clearBuffer()</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> flag</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">_write</span>(<span class="params">chunk, encoding, cb</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> <span class="built_in">this</span>.fd !== <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">this</span>.once(<span class="string">&#x27;open&#x27;</span>, <span class="function">() =&gt;</span> <span class="built_in">this</span>._write(chunk, encoding, cb))</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 开始文件写入操作</span></span><br><span class="line">    fs.write(<span class="built_in">this</span>.fd, chunk, <span class="built_in">this</span>.start, chunk.length, <span class="built_in">this</span>.writeOffset, <span class="function">(<span class="params">err, written</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.writeOffset += written</span><br><span class="line">      <span class="built_in">this</span>.writeLen -= written</span><br><span class="line"></span><br><span class="line">      cb &amp;&amp; cb()</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">_clearBuffer</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> data = <span class="built_in">this</span>.cache.deQueue()</span><br><span class="line">    <span class="keyword">if</span>(data) &#123;</span><br><span class="line">      <span class="comment">// 缓存队列中有任务，开始执行写入</span></span><br><span class="line">      <span class="built_in">this</span>._write(data.element.chunk, data.element.encoding, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        data.element.cb &amp;&amp; data.element.cb()</span><br><span class="line">        <span class="built_in">this</span>._clearBuffer()</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 无任务，则触发 drain 事件</span></span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">this</span>.needDrain) &#123;</span><br><span class="line">        <span class="built_in">this</span>.needDrain = <span class="literal">false</span></span><br><span class="line">        <span class="built_in">this</span>.emit(<span class="string">&#x27;drain&#x27;</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> wr = <span class="keyword">new</span> MyWriteStream(<span class="string">&#x27;test.txt&#x27;</span>, &#123;</span><br><span class="line">  highWaterMark: <span class="number">4</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">wr.on(<span class="string">&#x27;open&#x27;</span>, <span class="function">(<span class="params">fd</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;open ---&gt;&#x27;</span>, fd)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> flag = wr.write(<span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;写入成功&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(flag)</span><br><span class="line"></span><br><span class="line">flag = wr.write(<span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;写入成功2&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(flag)</span><br><span class="line"></span><br><span class="line">flag = wr.write(<span class="string">&#x27;3&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;写入成功3&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(flag)</span><br><span class="line"></span><br><span class="line">flag = wr.write(<span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;结束&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(flag)</span><br><span class="line"></span><br><span class="line">wr.once(<span class="string">&#x27;drain&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;drain 触发了&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="8-背压机制"><a href="#8-背压机制" class="headerlink" title="8. 背压机制"></a>8. 背压机制</h4><p><code>write() 的返回值和 drain 事件的关系：</code>drain 与写入速度 （限流）</p>
<p><code>背压机制</code>：Nodejs 的 stram 已经实现了数据可平滑流动的背压机制 （<code>pipe</code>函数）</p>
<p>没有背压机制存在的问题：<code>内存溢出、GC频繁调用、其他进程变慢</code></p>
<p><img src="https://cdn.nlark.com/yuque/0/2022/png/26238530/1656057452648-cc9c549c-9f9d-4b50-8a81-37859a6c7282.png#clientId=u2df1d1e1-dc24-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=349&id=u421e382c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=698&originWidth=1713&originalType=binary&ratio=1&rotation=0&showTitle=false&size=361013&status=done&style=none&taskId=ub801644f-7a3e-43b2-a318-a34b96812e9&title=&width=856.5" alt="image.png"><br><img src="https://cdn.nlark.com/yuque/0/2022/png/26238530/1656057608584-aff05347-468e-47a9-84d4-210b918dd06b.png#clientId=u2df1d1e1-dc24-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=380&id=u287c3da5&margin=%5Bobject%20Object%5D&name=image.png&originHeight=760&originWidth=1714&originalType=binary&ratio=1&rotation=0&showTitle=false&size=309526&status=done&style=none&taskId=u1dbdb6c9-5ec2-42b3-a03e-dad1f84975f&title=&width=857" alt="image.png"></p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://xiaofujun.gitee.io/2022/06/29/%E6%96%87%E4%BB%B6%E6%B5%81/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/nodejs/" rel="tag">nodejs</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/07/07/%E7%BD%91%E7%BB%9C%E4%BC%A0%E8%BE%93%E8%BF%87%E7%A8%8B%E4%B8%AD%E7%9A%84%E7%B2%98%E5%8C%85/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            网络传输过程中的粘包
          
        </div>
      </a>
    
    
      <a href="/2022/06/22/%E6%A8%A1%E5%9D%97%E5%8C%96/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">模块化</div>
      </a>
    
  </nav>

  
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> 小付君
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="君书"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>